package com.qf.flash.mvp.presenter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qf.flash.event.WXPayRespEvent;
import com.qf.flash.http.response.PayResponse;
import com.qf.flash.http.response.WxPayResponse;
import com.qf.flash.model.AliPayResult;
import com.qf.flash.mvp.contract.PayContract;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BasePresenter;
import com.qf.flashlib.config.Constants;
import com.qf.flashlib.sharedpreferences.SavePermanentSharePrefs;
import com.qf.flashlib.util.CheckApkExist;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.Map;


/**
 * 支付
 * 2018/4/4 15:09
 */
public class PayPresenterImpl extends BasePresenter<PayContract.View> implements PayContract.Presenter {
    private static final int ALI_PAY_FLAG = 1;

    private Activity mContext;
    private IWXAPI api;
    private PayReq req;

    public PayPresenterImpl(Activity mContext) {
        this.mContext = mContext;
        EventBus.getDefault().register(this);
    }

    @Override
    public void showPay(int payType, Object data) {
        switch (payType) {
            //支付宝
            case Constants.PAY_ALI:
                if (data instanceof String)
                    showAliPay((String) data);
                break;
            //微信
            case Constants.PAY_WX:
                if (CheckApkExist.checkApkExist(mContext, CheckApkExist.WEIXIN_PACKAGE)) {
                    Type type = new TypeToken<PayResponse<WxPayResponse>>() {}.getType();
                    PayResponse<WxPayResponse> response = new Gson().fromJson((String) data, type);
                    if (response != null)
                        showWXPay(response.getData());
                    else
                        FlashLib.showToast("支付参数异常");
                } else {
                    FlashLib.showToast("没有安装微信");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 调起支付宝
     */
    private void showAliPay(final String orderInfo) {
        /* 调起支付 */
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(mContext);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = ALI_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 调起微信
     */
    private void showWXPay(WxPayResponse resp) {
        String appId = resp.getAppid();
        if (TextUtils.isEmpty(appId))
            return;
        /* 保存AppID */
        SavePermanentSharePrefs.getInstance().setData(Constants.WX_APP_ID, appId);
        /* 初始化微信支付Api */
        api = WXAPIFactory.createWXAPI(mContext, appId);
        /* 创建PayReq实例 */
        req = new PayReq();
        req.appId = appId;
        req.partnerId = resp.getPartnerid();
        req.prepayId = resp.getPrepayid();
        req.nonceStr = resp.getNoncestr();
        req.timeStamp = String.valueOf(resp.getTimestamp());
        req.packageValue = resp.getPackageX();
        req.sign = resp.getSign();
        /* 将该APP注册到微信 */
        api.registerApp(appId);
        /* 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信 */
        api.sendReq(req);
    }

    /**
     * 支付宝回调
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ALI_PAY_FLAG:
                    @SuppressWarnings("unchecked")
                    AliPayResult payResult = new AliPayResult((Map<String, String>) msg.obj);
                    // 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功，该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    if (TextUtils.equals(resultStatus, "9000")) {
                        verifyPaymentResults();
                    } else {
                        if (mRootView != null)
                            mRootView.onPayFailed();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 微信支付回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWXPayResp(WXPayRespEvent event) {
        if (event == null || event.getResp() == null)
            return;
        switch (event.getResp().errCode) {
            //成功
            case 0:
                verifyPaymentResults();
                break;
            //失败：可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
            case -1:
                if (mRootView != null)
                    mRootView.onPayFailed();
                break;
            //无需处理。发生场景：用户不支付了，点击取消，返回APP。
            case -2:
                break;
            default:
                break;
        }
    }

    /**
     * 验证支付结果
     */
    private void verifyPaymentResults() {
        //暂时写死
        if (mRootView != null)
            mRootView.onPaySuccess();
    }

    @Override
    public void detachView() {
        super.detachView();
        EventBus.getDefault().unregister(this);
        this.mRootView = null;
    }
}
